<template>
  <div class="content-area">
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <div>
              <h2>报修管理</h2>
            </div>

            <el-select
                v-model="value"
                placeholder="选择某一小区"
                size="large"
                style="width: 240px; margin-left: 10px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>

            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
            <div class="table-header-container">
              <div class="search-container">
                <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                  <el-option label="按处理状态查询" value="processingStatus"></el-option>
                  <el-option label="按房屋id查询" value="houseId"></el-option>
                  <el-option label="按报修id查询" value="id"></el-option>
                </el-select>

                <el-input v-model="searchQuery"
                          :placeholder="
                  searchOption === 'processingStatus'? '待处理，处理中，已完成，已取消' :
                  '请输入查询关键词'
                "
                          class="search-input"></el-input>
                <el-button type="primary" @click="searchRepair" class="search-button">查询</el-button>
              </div>

              <el-button type="primary" @click="handleCommunity">增加记录</el-button>
            </div>
            <table v-if="repairForm && repairForm.data && repairForm.data.records.length > 0"
                   style="text-align: center; width: 100%; border-collapse: collapse;">
              <thead>
              <tr>
                <th style="width: 70px; height: 50px; border: 1px solid #eee;">维修id</th>
                <th style="width: 100px; height: 50px; border: 1px solid #eee;">房屋id</th>
                <th style="width: 170px; height: 50px; border: 1px solid #eee;">问题描述</th>
                <th style="width: 120px; height: 50px; border: 1px solid #eee;">创建时间</th>
                <th style="width: 120px; height: 50px; border: 1px solid #eee;">期望报修时间</th>
                <th style="width: 80px; height: 50px; border: 1px solid #eee;">报修状态</th>
                <th style="width: 100px; height: 50px; border: 1px solid #eee;">处理人员id</th>
                <th style="width: 120px; height: 50px; border: 1px solid #eee;">处理完成时间</th>
                <th style="width: 80px; height: 50px; border: 1px solid #eee;">维修反馈</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(item, index) in repairForm.data.records" :key="index" style="border: 1px solid #eee;">
                <td style="width: 70px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.id" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.houseId" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 170px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.repairContent" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.createTime" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.repairDate" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.processingStatus" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.handlerId" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.completionDate" disabled class="disabled-style"></el-input>
                </td>
                <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                  <el-input v-model="item.feedBack" disabled class="disabled-style"></el-input>
                </td>

              </tr>
              </tbody>
            </table>
            <div v-else-if="errorMessage">{{ errorMessage }}</div>
            <div v-else>暂无维修记录</div>
          </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="repairForm && repairForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[4, 6, 8]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="repairForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>

    </el-container>

    <el-dialog v-model="addDialogFormVisible" title="增加报修" width="500">
      <el-form :model="addForm">
        <el-form-item label="房屋id" :label-width="formLabelWidth">
          <el-input v-model="addForm.houseId" placeholder="请输入房屋id" />
        </el-form-item>
        <el-form-item label="问题描述" :label-width="formLabelWidth">
          <el-input v-model="addForm.repairContent" placeholder="请输入问题描述" />
        </el-form-item>
        <el-form-item label="期望报修时间" :label-width="formLabelWidth">
          <el-date-picker
              v-model="this.addForm.repairDate"
              type="date"
              placeholder="请选择期望报修时间"
              :picker-options="{
                shortcuts: false,
                format: 'yyyy-MM-dd',
                valueFormat: 'yyyy-MM-dd'
              }"
              :rules="{ required: true, message: '请选择期望报修时间', trigger: 'change' }"
          ></el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { ElSwitch } from 'element-plus';

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      repairForm: {
        id: "",
        houseId: "",
        repairContent: "",
        createTime: "",
        repairDate: "",
        processingStatus: "",
        handlerId: "",
        startDate: "",
        completionDate: "",
        feedBack: "",
      },
      userStatisticsPage: null,
      errorMessage: '',
      currentPage: 1,
      pageSize: 8,
      addDialogFormVisible: false,
      addForm: {
        houseId: "",
        repairContent: "",
        createTime: "",
        repairDate: "",
        processingStatus: "",
        handlerId: "",
        startDate: "",
        completionDate: "",
        feedBack: "",
      },
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      formLabelWidth: '120px',
      searchOption: '',
      showDialog: false,
      communityId: "",
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchData();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchData();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    handleCommunity(){
      if(this.communityId) {
        this.addDialogFormVisible = true;
      }else{
        ElMessage.info('请先选择小区')
      }
    },
    pageChange(url) {
      this.$router.push(url);
    },
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/repair/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityID: this.communityId
        };
        if (this.searchOption === 'processingStatus') {
          params.processingStatus = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        console.log('repair',response)
        this.repairForm = response.data;
        this.originalInfo = {...this.repairForm};
      } catch (error) {
        ElMessage.error('获取报修记录失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        const date = this.addForm.repairDate;
        if (date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          this.addForm.repairDate = `${year}-${month}-${day}`;
        }
        const response = await axios.post(`/api/repair/post/${this.addForm.houseId}`,  null,{
          headers: {
            Authorization: token
          },
          params:{
            houseId: this.addForm.houseId,
            content: this.addForm.repairContent,
            date: this.addForm.repairDate
          }
        });
        console.log(response.data)
        if (response.data.code === 200) {
          ElMessage.success('增加报修记录成功');
          this.addDialogFormVisible = false;
          this.fetchData();
        } else {
          ElMessage.error('增加报修记录失败,请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('增加报修记录时出错：' + error.message);
      }
    },
    async searchRepair() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'processingStatus') {
          const response = await axios.get('/api/repair/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityID: this.communityId,
              processingStatus: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.repairForm = response.data;
            this.originalInfo = {...this.repairForm };
          } else {
            ElMessage.error('查询报修信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'houseId') {
          const response = await axios.get(`/api/repair/house/${this.searchQuery}`, {
            headers: {
              Authorization: token
            }
          });
          if (response.data.code === 200) {
            this.repairForm.data.records = response.data.data;
            this.originalInfo = {...this.repairForm };
          } else {
            ElMessage.error('查询报修信息失败，请输入正确信息');
          }
        }else if (this.searchOption === 'id') {
          const response = await axios.get(`/api/repair/get/${this.searchQuery}`, {
            headers: {
              Authorization: token
            }
          });
          if (response.data.code === 200) {
            this.repairForm.data.records = response.data.data;
            this.originalInfo = {...this.repairForm };
            console.log("repair",response)
          } else {
            ElMessage.error('查询报修信息失败，请输入正确信息');
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #eee;
  padding: 8px;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}


.menu-header {
  padding: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 300px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}

.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}
</style>